// pages/orderInfo.js
const app = getApp()
import mode from '../../utils/mode.js'
import Dialog from '../../miniprogram_npm/@vant/weapp/dialog/dialog.js'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    dingYueOK:1,
    temIds:['ozvgibebCwysJJcuL0_qN26GWySVilWU2yCJOwqkumA'],
    codeUrl:'',//专属客服二维码路径
    showCodeImg:false,  //展示客服二维码
    showPayTrue:false,  //兑换积分产品支付成功页面
    isTest: 0,
    isConfirm: 0,//1从确认订单页跳转过来的
    orders_type: 1,//1普通订单   2积分订单
    count: 100000,
    isErval: -1,
    user_id: '',
    order: null,
    order_id: '',
    order_number: '',
    timeData: {},
    order_real_pay_price: '',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function ({ order_id, order_number, order_real_pay_price, orders_type = 1, isConfirm, isTest,ispay }) {
    // this.countDown();
    var info = wx.getStorageSync('uinfo')
    if (order_id) {
      this.setData({
        isTest,
        user_id: info.user.id,
        order_id,
        orders_type,
        isConfirm,
        order_number,
        order_real_pay_price,
        showPayTrue:false,
      })
    }else if(ispay==1){
      if(isTest==1){
        this.setData({
          isTest:1
        })
      }
      this.getService()
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.getOrdersInfo()
  },
  orderPayBtn () {
    wx.showLoading()
    let { order, order_id, user_id } = this.data
    order.orders_type == 1 && wx.login({
      success: (res) => {
        mode.getOpenid(res.code).then(item => {
          mode.userOrderPay({
            openid: item.data,
            out_trade_no: order.out_trade_no,
            totalPrice: order.order_real_pay_price
          }).then(item => {
            this.orderPay(item)
          })
        })
      }
    })
    order.orders_type == 2 && wx.$api.integralPay({ orders_id: order_id, user_id }).then(res => {
      this.orderPay(res)
    })
  },
  onClose(){//关闭二维码弹窗
    this.setData({
      showCodeImg:false
    })
  },
  orderPay (item) { //支付订单
    wx.hideLoading()
    var newObj = JSON.parse(item.data)
    wx.requestPayment({
      nonceStr: newObj.nonceStr,
      package: newObj.package,
      paySign: newObj.paySign,
      timeStamp: newObj.timeStamp,
      signType: 'MD5',
      success: (res) => {
        // if(this.data.orders_type==2||this.data.is_test==1||this.data.order.remarks=='体验装订单'){ //   积分兑换产品订单
          this.getService()
        // }else{ //其他类型订单
        //   wx.showToast({
        //     title: '支付成功',
        //     icon: 'success',
        //     duration: 1500,
        //     mask: true
        //   })
        //   setTimeout(async () => {
        //     await this.getOrdersInfo(false)
        //   }, 1500)
        // }
        
      },
      fail (res) {
        console.log(res)
        wx.showToast({
          title: '支付失败',
          icon: 'error',
          duration: 2000
        })
      }
    })
  },
  getService () {  //获取专属客服二维码
    var that = this
    wx.$api.getServiceInfo().then(res=>{
            wx.hideLoading()
            that.setData({
                codeUrl: res.data,
                showPayTrue:true
            })
    })
},
setInfo(){   //提示订阅消息
  let that = this
  wx.requestSubscribeMessage({
      tmplIds: that.data.temIds,
      success (res) {
          if(res[that.data.temIds[0]]=='reject'){//拒绝
            console.log('已拒绝');
            that.setData({
                dingYueOK:0
            })
          }else{  //允许
            that.setData({
                dingYueOK:2
            })
              that.sendSetYue()
          }
      },
      fail(error){
          that.setData({
              dingYueOK:1
          })
      }
    })
},
sendSetYue(){
  let that = this
  wx.$api.sendTemplate({
          user_id: that.data.user_id,
          type: 2,
          order_id:that.data.order.id,
          order_type:that.data.order.orders_type
      }).then(res=>{
          if(res.code>0){
            console.log('订阅成功');
          }else{
              wx.showToast({
                title: res.msg,
                icon:'none'
              })
          }
  })
},
  orderStatus (val) {
    //订单状态 0待支付 1待发货 2待收货 3已收货 4已取消 5已删除 默认0
    let type = ['待支付', ' 待发货', ' 待收货', '已收货 ', '已取消', '已删除']
    return type[val]
  },
  async finished () {
    console.log('订单已过期')
    // await this.getOrdersInfo(true)
    wx.showModal({
      title: '提示',
      content: '订单已过期!',
      showCancel: false,
      success: function (res) {
        app.backPage()
      }
    })
  },
  afterSales (e) {//去售后
    app.goUrl(`/pages/applyAfter/applyAfter?order_id=${this.data.order_id}`)
  },
  changeAddress () {//修改订单地址
    // app.goUrl(`/pages/address-save/address-save?type=3&orders_type=${this.data.orders_type}&order_id=${this.data.order_id}`)
    app.goUrl(`/pages/address/address?addressType=1&orderId=${this.data.order_id}&addressId=${this.data.order.address.address_id}&integral=${this.data.order.status_type == 1 ? '1' : ''}`)
  },
  //再次购买
  buyAgain (e) {
    let goods = this.data.order
    if (goods.orders_type == 2) {
      let type = ['', 'integral_good_id', 'integral_coupon_id']
      app.goUrl(`/pages/goods-details/goods-details?id=${goods[type[goods.status_type]]}&type=${goods.status_type}`)
      return
    }
    if (!goods.order_goods) return
    let goods_info = goods.order_goods.map(v => {
      return {
        goods_id: v.goods_id,
        number: v.number
      }
    })
    app.goUrl(`/pages/settlement/settlement?goods_info=${JSON.stringify(goods_info)}`)
  },
  async confirmOrder () {
    Dialog.confirm({
      zIndex: 999,
      closeOnClickOverlay: true,
      width: '280px',
      theme: '',
      title: '确认已收到货',
      message: '为了保障售后权益，请检查后再确认收货',
    })
      .then(async () => {
        wx.showLoading({
          title: '确认收货中...',
          mask: true,
        })
        let { code, data, msg } = await mode.confirmOrder({
          order_id: this.data.order_id,
          order_type: this.data.orders_type,
        })
        wx.hideLoading()
        if (code == 1) {
          wx.showToast({ title: '确认收货成功!' })
          setTimeout(() => {
            this.getOrdersInfo(false)
          }, 1500)
        } else wx.showToast({ title: msg, icon: 'none' })
      })
      .catch(() => {
      })
    return
    wx.showModal({
      title: '确认已收到货',
      content: '为了保障售后权益，请检查后再确认收货',
      showCancel: true,
      cancelText: '取消',
      cancelColor: '#000000',
      confirmText: '确定',
      confirmColor: '#277CE3',
      success: async (result) => {
        if (result.confirm) {
          wx.showLoading({
            title: '确认收货中...',
            mask: true,
          })
          let { code, data } = await mode.confirmOrder({
            order_id: this.data.order_id,
            order_type: this.data.orders_type,
          })
          wx.hideLoading()
          if (code == 1) {
            wx.showToast({ title: '确认收货成功!' })
            this.getOrdersInfo(false)
          }
        }
      },
      fail: () => { },
      complete: () => { }
    })
  },
  async getOrdersInfo (type = true) {
    if (type) wx.showLoading({ mask: true })
    if(!this.data.order_id){
      return
    }
    let { code, data } = await mode.getOrdersInfo({
      orders_type: this.data.orders_type,
      user_id: this.data.user_id,
      id: this.data.order_id
    })
    if (type) wx.hideLoading()
    if (code && data) {
      if (data.orders_type == 2) {
        ////订单状态 0待支付 1待发货 2待收货 3已收货 4已取消 5已删除 默认0
        data.order_status = [100, 200, 300, 400].findIndex(v2 => v2 == data.status) + 1
      }
      let num = 0
      if (Array.isArray(data.order_goods)) {
        data.order_goods.forEach(x => {
          num += (x.price * x.number)
        })
        data.totalPrice = parseFloat(num).toFixed(2)
      }
      data.status_text = (data.status_text == '已完成' && !data.exchange_order) ? '交易完成' : data.status_text
      this.setData({
        order: data || {},
        count: data.order_over_pay_time ? new Date(data.order_over_pay_time.replace(/\-/g, '/')).getTime() - new Date().getTime() : '',
      })
      const countDown = this.selectComponent('.control-count-down')
      countDown && countDown.start()
    }
  },
  onChange (e) {
    this.setData({
      timeData: e.detail,
    })
  },
  countDown () {
    // return
    clearInterval(this.data.isErval)
    let isErval = setInterval(() => {
      let time = new Date(`2022/01/01 ${this.data.count}`).getTime() - 1000
      let date = new Date(time),
        hours = Number(date.getHours()),
        minute = date.getMinutes(),
        seconds = date.getSeconds()
      if (!hours && !minute && !seconds) {
        console.log('订单已过期')
        wx.showModal({
          title: '提示',
          content: '订单已过期!',
          showCancel: false,
          success: function (res) {
            app.backPage()
          }
        })
        clearInterval(this.data.isErval)
      }
      this.setData({
        count: `${hours > 9 ? hours : '0' + hours}:${minute > 9 ? minute : '0' + minute}:${seconds > 9 ? seconds : '0' + seconds}`
      })
    }, 1000)
    this.setData({
      isErval
    })

  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    clearInterval(this.data.isErval)
    const pages = getCurrentPages()
    const prevPage = pages[pages.length - 2] //上一个页面
    if (prevPage.route == 'pages/settlement/settlement') {
      app.goUrl('/pages/exclusive/exclusive', true)
    }
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  async onPullDownRefresh () {
    //在当前页面显示导航条加载动画
    wx.showNavigationBarLoading()
    await this.getOrdersInfo()
    wx.showToast({ title: '刷新成功!', icon: 'none' })
    //隐藏导航条加载动画
    wx.hideNavigationBarLoading()
    //停止下拉刷新
    wx.stopPullDownRefresh()
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  // kefu
  handleContact () {
    console.log(`%c✅=> `, 'color:#ff7b54;font-size:16px;', '点击客服icon')
  },
  setClipboardData () {
    wx.setClipboardData({
      data: this.data.order.order_express.express_no || ''
    })
  }
})